package com.lepton.wifidog;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class mysqlHandle {
	private Connection conn;
	private PreparedStatement pstm;
	private String conString = "jdbc:mysql://172.16.8.143:3306/test";
	private String dbUser = "root";
	private String dbPwd = "Lepton1234";
	
	private static mysqlHandle mysql;
	
	private mysqlHandle(){}
	
	public static mysqlHandle getInstance(){
		if(mysql == null){
			mysql = new mysqlHandle();
		}
		
		return mysql;
	}
	
	private void getCon(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(conString, dbUser, dbPwd);
		}catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	private void excute(String sql){
		if(conn == null)
			getCon();
		
		try {
			pstm = conn.prepareStatement(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public ResultSet getResultSet(String sql){
		excute(sql);
		System.out.println("sql = " + sql);
		try {
			return pstm.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	public String getFirstUnit(String sql){
		excute(sql);
		
		String value;
		ResultSet rs;
		try {
			rs = pstm.executeQuery();
			rs.next();
			
			value = rs.getString(1);
			
			rs.close();
			return value;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public int getInt(String sql){
		this.excute(sql);
		
		try {
			return pstm.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return 0;
	}
	
	public void closeMysql(){
		try {
			pstm.cancel();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
